package dao;

import java.util.ArrayList;
import java.util.List;

import domain.Payment;

public class PaymentDAO extends GenericDAO<Payment> {

	private static PaymentDAO instance;
	
	public static PaymentDAO getInstance() {
		if (instance == null) {
			instance = new PaymentDAO();
		}
		return instance;
	}

	@Override
	public Payment store(Payment entity) {
		if (entity.getId() != null) {
			return update(entity);
		}
		entity.setId(BalanceDAO.sequenceId++);
		entity.setVersion(0);
		this.entities.put(entity.getId(), entity.clone());
		return entity;
	}

	@Override
	public Payment update(Payment entity) {
		if (entity.getId() == null) {
			return store(entity);
		} else if (entity.getVersion().equals(find(entity.getId()).getVersion())) {
			return entity;
		}
		entity.incVersion();
		this.entities.put(entity.getId(), entity.clone());
		return entity;
	}
	
	@Override
	public List<Payment> getAll() {
		List<Payment> objects = new ArrayList<Payment>();
		for (Payment entity : entities.values()) {
			objects.add(entity.clone());
		}
		return objects;
	}
	
	public List<Payment> getAllByBalanceMonth(Integer id) {
		List<Payment> payments = new ArrayList<Payment>();
		for (Payment payment : getAll()) {
			if (payment.getBalanceMonth().getId().equals(id)) {
				payments.add(payment);
			}
		}
		return payments;
	}
}
